package com.sayx.lib_common

import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.text.TextUtils
import com.blankj.utilcode.util.LogUtils
import com.bytedance.hume.readapk.HumeSDK
import com.kwai.monitor.payload.TurboHelper
import com.tencent.bugly.crashreport.CrashReport
import io.flutter.BuildConfig
import io.flutter.plugin.common.BasicMessageChannel
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.JSONMessageCodec
import org.json.JSONObject

class AndroidChannel(private val applicationContext: Context) : BasicMessageChannel.MessageHandler<Any> {

    private lateinit var channel: BasicMessageChannel<Any>

    fun create(binaryMessenger: BinaryMessenger) {
        val channelName = CommonConstants.APP_CHANNEL_NAME
        channel =
            BasicMessageChannel(binaryMessenger, channelName, JSONMessageCodec.INSTANCE)
        channel.setMessageHandler(this)
    }

    override fun onMessage(message: Any?, callback: BasicMessageChannel.Reply<Any>) {
        message?.let {
            if (message is JSONObject) {
                LogUtils.d("Flutter Message:${message}")
                when (val method = message.getString(CommonConstants.METHOD)) {
                    CommonConstants.RUNTIME_CHANNEL -> {
                        val channelName = getChannelName()
                        callback.reply(channelName)
                        return
                    }

                    CommonConstants.ANDROID_SYSTEM_VERSION -> {
                        val version = Build.VERSION.SDK_INT
                        callback.reply(version)
                        return
                    }

                    CommonConstants.INIT_NATIVE_SDK -> {
                        initSDK()
                        callback.reply(true)
                        return
                    }

                    else -> {
                        LogUtils.e("Flutter call:${method}, but Native not Response")
                        callback.reply(null)
                    }
                }
            } else {
                LogUtils.e("Flutter Message:${message}, but not JsonObject")
                callback.reply(null)
            }
        } ?: {
            LogUtils.e("Flutter Message is Null")
        }
        callback.reply(null)
    }

    /**
     * 初始化三方sdk
     */
    private fun initSDK() {
        CrashReport.initCrashReport(applicationContext, "ad7be91ed6", BuildConfig.DEBUG)
    }

    /**
     * 获取当前运行渠道名称
     */
    private fun getChannelName(): String? {
        var channelName = try {
            val applicationInfo = applicationContext.packageManager.getApplicationInfo(
                applicationContext.packageName,
                PackageManager.GET_META_DATA
            )
            applicationInfo.metaData?.getString("CHANNEL_NAME")
        } catch (e: Exception) {
            "unknown"
        }
        if (channelName == "kuaishou") {
            // 快手需读取快手分包渠道号
            val channelCode = TurboHelper.getChannel(applicationContext)
            LogUtils.d("getChannelName->channelName=$channelName, channelCode=$channelCode")
            if (!TextUtils.isEmpty(channelCode)) {
                channelName =  "$channelName-$channelCode"
            }
        }
        if (channelName == "douyin") {
            // 抖音需读取抖音分包渠道号
            val channelCode = HumeSDK.getChannel(applicationContext)
            LogUtils.d("getChannelName->channelName=$channelName, channelCode=$channelCode")
            if (!TextUtils.isEmpty(channelCode)) {
                channelName = "$channelName-$channelCode"
            }
        }
        LogUtils.d("getChannelName:$channelName")
        return channelName
    }

    /**
     * 原生端发送信息给Flutter
     */
    fun sendMessage(message: Any?) {
        channel.send(message) { reply ->
            LogUtils.d("Flutter Reply:$reply")
        }
    }
}